package com.example.demo.多线程.线程通信;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Book {
    private int number = 10;
    private final ReentrantLock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();

    // 还书
    public void increment() {
        lock.lock();
        try {
            while (number == 10) {
                condition.await();
            }
            System.out.println(Thread.currentThread().getName() + ",还了第" + number++ + "书");
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    // 借书
    public void decrement() {
        lock.lock();
        try {
            while (number == 0) {
                condition.await();
            }
            System.out.println(Thread.currentThread().getName() + ",借出第" + number-- + "书");
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
